<template>
  <div>
    <h2>产品列表</h2>

    <!-- 查询区域 -->
    <div class="search-container">
      <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          style="width: 200px; margin-right: 10px"
      />
      <el-input
          v-model="queryParams.description"
          placeholder="请输入产品描述"
          clearable
          style="width: 200px; margin-right: 10px"
      />
      <el-button type="primary" @click="loadProducts" :loading="loading">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="showAddDialog">新增产品</el-button>
    </div>

    <!-- 产品表格 -->
    <el-table 
      :data="products" 
      style="width: 100%" 
      v-loading="loading"
      border
      stripe
    >
              <el-table-column prop="productId" label="产品ID" width="150" show-overflow-tooltip sortable />
        <el-table-column prop="productName" label="产品名称" width="200" show-overflow-tooltip sortable />
        <el-table-column prop="description" label="产品描述" show-overflow-tooltip sortable />
        <el-table-column prop="createTime" label="创建时间" width="180" sortable />
        <el-table-column prop="updateTime" label="更新时间" width="180" sortable />
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="editProduct(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteProduct(scope.row)">删除</el-button>
          <el-button size="small" type="info" @click="viewProcessRoute(scope.row)">查看工艺</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="pagination.pageNum"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, prev, pager, next, jumper" background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; text-align: right"
    />

    <!-- 产品编辑对话框 -->
    <el-dialog v-model="showDialog" :title="dialogTitle" width="500px">
      <el-form 
        ref="productFormRef"
        :model="formData" 
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="产品ID" v-if="isEdit">
          <el-input v-model="formData.productId" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input 
            v-model="formData.productName" 
            placeholder="请输入产品名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="产品描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            placeholder="请输入产品描述"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="saveProduct" :loading="saveLoading">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

const API_BASE_URL = 'http://117.72.45.141:8091';

// 定义事件发射器
const emit = defineEmits(['view-process-route']);

// 响应式数据
const products = ref([]);
const loading = ref(false);
const saveLoading = ref(false);
const showDialog = ref(false);
const isEdit = ref(false);
const dialogTitle = ref('添加产品');
const productFormRef = ref(null);

// 查询参数
const queryParams = reactive({
  productName: '',
  description: '',
  pageNum: 1,
  pageSize: 10
});

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 表单数据
const formData = reactive({
  productId: '',
  productName: '',
  description: ''
});

// 表单验证规则
const formRules = {
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' },
    { min: 1, max: 100, message: '产品名称长度在 1 到 100 个字符', trigger: 'blur' },
    { validator: checkProductName, trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '产品描述不能超过 500 个字符', trigger: 'blur' }
  ]
};

// 检查产品名称是否重复
async function checkProductName(rule, value, callback) {
  if (!value) {
    callback();
    return;
  }
  
  try {
    const response = await axios.get(`${API_BASE_URL}/api/product/check-name`, {
      params: {
        productName: value,
        excludeId: isEdit.value ? formData.productId : ''
      },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      // 后端返回true表示名称可用，false表示已存在
      if (response.data.data === false) {
        callback(new Error('产品名称已存在，请使用其他名称'));
      } else {
        callback();
      }
    } else {
      callback();
    }
  } catch (error) {
    console.error('检查产品名称失败:', error);
    callback();
  }
}

// 加载产品列表
const loadProducts = async () => {
  loading.value = true;
  try {
    const response = await axios.post(`${API_BASE_URL}/api/product/page`, {
      ...queryParams,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.success) {
      products.value = response.data.data.records || [];
      pagination.total = response.data.data.total || 0;
    } else {
      ElMessage.error(response.data.message || '加载产品列表失败');
    }
  } catch (error) {
    console.error('加载产品列表失败:', error);
    ElMessage.error('加载产品列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  queryParams.productName = '';
  queryParams.description = '';
  pagination.pageNum = 1;
  loadProducts();
};

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  pagination.pageNum = 1;
  loadProducts();
};

const handleCurrentChange = (val) => {
  pagination.pageNum = val;
  loadProducts();
};

// 显示添加对话框
const showAddDialog = () => {
  Object.assign(formData, {
    productId: '',
    productName: '',
    description: ''
  });
  isEdit.value = false;
  dialogTitle.value = '添加产品';
  showDialog.value = true;
  // 清除验证结果
  if (productFormRef.value) {
    productFormRef.value.clearValidate();
  }
};

// 编辑产品
const editProduct = (product) => {
  Object.assign(formData, product);
  isEdit.value = true;
  dialogTitle.value = '编辑产品';
  showDialog.value = true;
  // 清除验证结果
  if (productFormRef.value) {
    productFormRef.value.clearValidate();
  }
};

// 保存产品
const saveProduct = async () => {
  if (!productFormRef.value) return;
  
  try {
    const valid = await productFormRef.value.validate();
    if (!valid) return;
  } catch (error) {
    return;
  }
  
  saveLoading.value = true;
  try {
    const url = `${API_BASE_URL}/api/product`;
    const method = isEdit.value ? 'put' : 'post';
    
    const response = await axios[method](url, formData, {
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });

    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '产品更新成功' : '产品添加成功');
      showDialog.value = false;
      loadProducts();
    } else {
      ElMessage.error(response.data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存产品失败:', error);
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message);
    } else {
      ElMessage.error('保存失败，请检查网络连接');
    }
  } finally {
    saveLoading.value = false;
  }
};

// 删除产品
const deleteProduct = async (product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品 "${product.productName}" 吗？此操作不可逆。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await axios.delete(`${API_BASE_URL}/api/product/${product.productId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
    ElMessage.success('产品删除成功');
      loadProducts();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
    console.error('删除产品失败:', error);
      ElMessage.error('删除失败，请检查网络连接');
  }
  }
};

// 查看工艺路线
const viewProcessRoute = (product) => {
  // 发射事件到父组件
  emit('view-process-route', product);
};

onMounted(() => {
  loadProducts();
});
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-result {
  margin: 10px 0;
  padding: 8px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 4px;
  color: #1e40af;
}

.search-result.no-match {
  background-color: #fef2f2;
  border-color: #fecaca;
  color: #dc2626;
}
</style>